import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import { AtButton } from 'taro-ui';
import React, { useEffect, useState } from 'react';

interface ShareButtonProps {
  title: string;
  path: string;
  imageUrl?: string;
  onShareSuccess?: (res: any) => void;
  onShareFail?: (err: any) => void;
}

export const ShareButton: React.FC<ShareButtonProps> = ({
  title,
  path,
  imageUrl = '',
  onShareSuccess,
  onShareFail,
}) => {
  const [canIUseShareAppMessage, setCanIUseShareAppMessage] = useState(false);

  useEffect(() => {
    // 检测API兼容性
    setCanIUseShareAppMessage(Taro.canIUse('button.open-type.share'));
  }, []);

  // 处理分享按钮点击
  const handleShare = () => {
    Taro.showShareMenu({
      withShareTicket: true,
    }).catch((err) => {
      console.error('显示分享菜单失败:', err);
      if (onShareFail) onShareFail(err);
    });
  };

  // 页面分享配置
  const onShareAppMessage = () => ({
    title,
    path,
    imageUrl,
    success: (res) => {
      console.log('分享成功:', res);
      if (onShareSuccess) onShareSuccess(res);
    },
    fail: (err) => {
      console.error('分享失败:', err);
      if (onShareFail) onShareFail(err);
    },
  });

  // 朋友圈分享配置
  const onShareTimeline = () => ({
    title,
    query: path.split('?')[1] || '',
    imageUrl,
  });

  return (
    <View>
      {canIUseShareAppMessage ? (
        <AtButton type="primary" openType="share" className="share-btn">
          分享
        </AtButton>
      ) : (
        <AtButton type="primary" onClick={handleShare} className="share-btn">
          分享
        </AtButton>
      )}
    </View>
  );
};
